<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/10/13
 * Time: 10:36 AM
 */

namespace app\zyhsapi\model;

use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\zyhsapi\lib\OrdersLib;
use think\Config;
use think\Env;
use think\Log;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsUserAccount extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_user_account';
    protected $cacheModel = 'user.coin';

    /**
     * 用户准币余额
     * @param $uid
     * @return int
     * @throws \Exception
     */
    public function getCoinNum($uid)
    {
        $user_coin = $this->getUserCoinFromCache($uid);
        return $user_coin ? (int)$user_coin['balance'] : 0;
    }


    /**
     * 获取用户准币
     * @param $uid
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function getUserCoinFromCache($uid)
    {
        $data = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $uid)->getDataAndSet(function () use ($uid)
        {
            try
            {
                $data = $this->field('id,uid,status,password,set_password_time,balance,total_amount,consume_price,total_coin,consume_coin')->where(['uid' => $uid])->findOrFail()->toArray();
                if ($data['status'] === 2)
                {
                    throw new ApiException('当前账户钱包已被冻结');
                }
            }
            catch (\Exception $e)
            {
                $data = [];
            }
            return $data;
        });
        //若用户无准币数据则生成
        if (!$data)
        {
            $data = [
                'uid' => $uid,
                'status' => 1,
                'balance' => 0,
                'total_amount' => 0,
                'consume_price' => 0,
                'total_coin' => 0,
                'consume_coin' => 0,
                'last_time' => 0,
                'create_time' => time(),
                'update_time' => 0,
                'password' => '',
                'set_password_time' => 0
            ];
            $this->SaveData($uid, $data);
        }
        return $data;
    }

    /**
     * 充值准币
     * @param $uid
     * @param $data
     * @return false|int|string
     * @throws \Exception
     */
    public function SaveData($uid, $data)
    {
        try
        {
            $id = $this->insertGetId($data);
        }
        catch (\Exception $e)
        {
            Log::write($uid . '用户充值余额数量失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】');
            return false;
        }
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache();
        return $id;
    }

    /**
     * 更新用户准币数量
     * @param int $uid
     * @param array $data
     * @param array $where
     * @return bool|int|string
     * @throws \Exception
     */
    public function UpdateData($uid, $data, $where)
    {
        try
        {
            $this->where($where)->update($data);
        }
        catch (\Exception $e)
        {
            Log::write($uid . '更新用户余额数量失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】');
            return false;
        }
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache();
        return true;
    }

    /**
     * 数据库批量获取用户准币明细
     * @param array $ids
     * @param array $type
     * @param string $sortType
     * @return array|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $field = 'id,uid,consumer_type,order_type,gid,pray_date,total_amount,coin_num,balance,order_id,trade_type,create_time,update_time,extend';
        if ($ids)
        {
            $where = ['id' => ['in', $ids], 'status' => 1];
        } else
        {
            $where = ['uid' => $type[0], 'status' => 1];
        }
        try
        {
            $data = $this->where($where)->order('id', 'DESC')->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    /**
     * 获取准币商品
     * @return mixed|null
     */
    public function coinGoods($isIos, $user)
    {
        $goodsConfig = Config::get('zyhsgoods');
        //获取准币商品信息
        if ($isIos)
        {
            $goods = $goodsConfig['ios_coin_goods'];

        } else
        {
            $goods = $goodsConfig['android_coin_goods'];
            $coinTel = config('zyhsapp.coin_mobile');
            //准币测试号,准币价格为1分钱
            if (isset($coinTel[$user['tel']]))
            {
                array_walk($goods, static function (&$item)
                {
                    $item['now_prize'] = 0.01;
                    $item['received_price'] = 0.01;
                });
            }
        }
        return $goods;
    }

    /**
     * 准币账户信息更新(充值时需获取明细里的准币数,不可直接金额计算准币数,因内部测试金额是一分钱)
     * @param $uid
     * @param int $consumer_type 准币变更类型
     * @param int $coin_num 准币数
     * @throws \Exception
     */
    public function updateCoinInfo($uid, $consumer_type, $coin_num)
    {
        $total_amount = OrdersLib::getOrderCoinTotalAmount($coin_num);
        //获取用户钱包信息
        $userCoin = $this->getUserCoinFromCache($uid);
        switch ($consumer_type)
        {
            case 1://充值
            case 3://赠送
            case 4://准币购买商品退款
                $balance = $userCoin['balance'] + $coin_num;
                $total_amount = $userCoin['total_amount'] + $total_amount;
                $total_coin = $userCoin['total_coin'] + $coin_num;
                //更新用户钱包金额
                $this->UpdateData($uid, ['balance' => $balance, 'total_amount' => $total_amount, 'total_coin' => $total_coin, 'update_time' => time()], ['uid' => $uid]);
                break;
            case 2://消费
            case 5://打赏
                $balance = $userCoin['balance'] - $coin_num;
                $consume_price = $userCoin['consume_price'] + $total_amount;
                $consume_coin = $userCoin['consume_coin'] + $coin_num;
                //更新用户钱包金额
                $this->UpdateData($uid, ['balance' => $balance, 'consume_price' => $consume_price, 'consume_coin' => $consume_coin, 'update_time' => time()], ['uid' => $uid]);
                break;
            case 6://准币充值退款
                $balance = $userCoin['balance'] - $coin_num;
                $total_amount = $userCoin['total_amount'] - $total_amount;
                $total_coin = $userCoin['total_coin'] - $coin_num;
                //更新用户钱包金额
                $this->UpdateData($uid, ['balance' => $balance, 'total_amount' => $total_amount, 'total_coin' => $total_coin, 'update_time' => time()], ['uid' => $uid]);
                break;
        }
    }
}
